# 导入依赖包
import os
import sys
import re
import uuid
import time
import json
import asyncio
from contextlib import asynccontextmanager
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, StreamingResponse
import uvicorn
from langchain_openai import ChatOpenAI
from crewai import Agent, Crew, Task, Process

from smart_supermarket.crew import SmartSupermarketCrew
from tools.database_tool import DatabaseTool
from tools.inventory_tool import InventoryTool
from tools.payment_tool import PaymentTool
from tools.custom_tool import CustomTool
from smart_supermarket.tools.nlp_tool import NLPTool
from smart_supermarket.tools.product_tool import ProductTool
from smart_supermarket.tools.logger_tool import LoggerTool

# 定义Query类
class Query(BaseModel):
    text: str

# 模型全局参数配置  根据自己的实际情况进行调整
# openai模型相关配置 根据自己的实际情况进行调整
OPENAI_API_BASE = "https://api.wlai.vip/v1"
OPENAI_CHAT_API_KEY = "sk-6Sk3Sp0HGr8uBYKuB5B9308aD7124d988eD690Ba7eAb8b4c"
OPENAI_CHAT_MODEL = "gpt-4o"
# OPENAI_CHAT_MODEL = "gpt-4o-mini"
# 非gpt大模型相关配置(oneapi方案 通义千问为例) 根据自己的实际情况进行调整
ONEAPI_API_BASE = "http://localhost:3000/v1"
ONEAPI_CHAT_API_KEY = "sk-M7C40emVuDhbUmwhD560F8A8F4D144Bd974aD5BcE2D24d9d"
ONEAPI_CHAT_MODEL = "ERNIE-Speed-128K"
# 本地大模型相关配置(Ollama方案 llama3.1:latest为例) 根据自己的实际情况进行调整
OLLAMA_API_BASE = "http://192.168.2.9:11434/v1"
OLLAMA_CHAT_API_KEY = ""
OLLAMA_CHAT_MODEL = "llama3.1:latest"

# 初始化LLM模型
model = None
# API服务设置相关  根据自己的实际情况进行调整
PORT = 8014  # 服务访问的端口
# openai:调用gpt大模型;oneapi:调用非gpt大模型;ollama:调用本地大模型
# MODEL_TYPE = "openai"
MODEL_TYPE = "oneapi"

# 初始化工具
db_tool = None
nlp_tool = None
inventory_tool = None
product_tool = None
logger_tool = None

# 定义Message类
class Message(BaseModel):
    role: str
    content: str


# 定义ChatCompletionRequest类
class ChatCompletionRequest(BaseModel):
    messages: List[Message]
    stream: Optional[bool] = False


# 定义ChatCompletionResponseChoice类
class ChatCompletionResponseChoice(BaseModel):
    index: int
    message: Message
    finish_reason: Optional[str] = None


# 定义ChatCompletionResponse类
class ChatCompletionResponse(BaseModel):
    id: str = Field(default_factory=lambda: f"chatcmpl-{uuid.uuid4().hex}")
    object: str = "chat.completion"
    created: int = Field(default_factory=lambda: int(time.time()))
    choices: List[ChatCompletionResponseChoice]
    system_fingerprint: Optional[str] = None


# 定义了一个异步函数lifespan，它接收一个FastAPI应用实例app作为参数。这个函数将管理应用的生命周期，包括启动和关闭时的操作
# 函数在应用启动时执行一些初始化操作
# 函数在应用关闭时执行一些清理操作
# @asynccontextmanager 装饰器用于创建一个异步上下文管理器，它允许在yield之前和之后执行特定的代码块，分别表示启动和关闭时的操作
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 启动时执行
    # 申明引用全局变量，在函数中被初始化，并在整个应用中使用
    global MODEL_TYPE, model, db_tool, nlp_tool, inventory_tool, product_tool, logger_tool
    global ONEAPI_API_BASE, ONEAPI_CHAT_API_KEY, ONEAPI_CHAT_MODEL
    global OPENAI_API_BASE, OPENAI_CHAT_API_KEY, OPENAI_CHAT_MODEL
    global OLLAMA_API_BASE, OLLAMA_CHAT_API_KEY, OLLAMA_CHAT_MODEL
    # 根据自己实际情况选择调用model和embedding模型类型
    try:
        # 初始化日志工具
        logger_tool = LoggerTool()
        logger_tool.log_workflow("正在初始化服务...", "INFO")
        
        # 根据MODEL_TYPE选择初始化对应的模型,默认使用gpt大模型
        if MODEL_TYPE == "oneapi":
            # 实例化一个oneapi客户端对象
            logger_tool.log_workflow(f"使用OneAPI模型: {ONEAPI_CHAT_MODEL}", "INFO")
            model = ChatOpenAI(
                base_url=ONEAPI_API_BASE,
                api_key=ONEAPI_CHAT_API_KEY,
                model=ONEAPI_CHAT_MODEL,  # 本次使用的模型
                temperature=0.7,  # 发散的程度
                request_timeout=60,
                max_retries=2,
            )
        elif MODEL_TYPE == "ollama":
            # 实例化一个本地模型客户端对象
            logger_tool.log_workflow(f"使用Ollama本地模型: {OLLAMA_CHAT_MODEL}", "INFO")
            os.environ["OPENAI_API_KEY"] = "NA"
            model = ChatOpenAI(
                base_url=OLLAMA_API_BASE,  # 请求的API服务地址
                api_key=OLLAMA_CHAT_API_KEY,  # API Key
                model=OLLAMA_CHAT_MODEL,  # 本次使用的模型
                temperature=0.7,  # 发散的程度
                # timeout=None,# 服务请求超时
                # max_retries=2,# 失败重试最大次数
            )
        else:
            # 实例化一个OpenAI客户端对象
            logger_tool.log_workflow(f"使用OpenAI模型: {OPENAI_CHAT_MODEL}", "INFO")
            model = ChatOpenAI(
                base_url=OPENAI_API_BASE,  # 请求的API服务地址
                api_key=OPENAI_CHAT_API_KEY,  # API Key
                model=OPENAI_CHAT_MODEL,  # 本次使用的模型
                # temperature=0.7,# 发散的程度，一般为0
                # timeout=None,# 服务请求超时
                # max_retries=2,# 失败重试最大次数
            )

        # 初始化工具
        logger_tool.log_workflow("初始化工具...", "INFO")
        db_tool = DatabaseTool()
        nlp_tool = NLPTool(model)
        inventory_tool = InventoryTool(db_tool, nlp_tool)
        product_tool = ProductTool(db_tool, nlp_tool)

        logger_tool.log_workflow("服务初始化完成", "INFO")

    except Exception as e:
        if logger_tool:
            logger_tool.log_workflow(f"初始化过程中出错: {str(e)}", "ERROR")
        else:
            print(f"初始化过程中出错: {str(e)}")
        # raise 关键字重新抛出异常，以确保程序不会在错误状态下继续运行
        raise

    # yield 关键字将控制权交还给FastAPI框架，使应用开始运行
    # 分隔了启动和关闭的逻辑。在yield 之前的代码在应用启动时运行，yield 之后的代码在应用关闭时运行
    yield
    # 关闭时执行
    if logger_tool:
        logger_tool.log_workflow("正在关闭服务...", "INFO")
    else:
        print("正在关闭服务...")


# lifespan 参数用于在应用程序生命周期的开始和结束时执行一些初始化或清理工作
app = FastAPI(title="智能超市系统API", lifespan=lifespan)


# POST请求接口，处理智能超市的用户请求
@app.post("/smart_supermarket/chat")
async def process_query(query: Query):
    """处理用户查询"""
    if not model:
        raise HTTPException(status_code=500, detail="服务未初始化")
    
    try:
        # 记录用户交互
        logger_tool.log_user_interaction(query.text)
        
        # 记录日志
        logger_tool.log_workflow(f"收到用户查询: {query.text}", "INFO")
        logger_tool.log_workflow("分析用户意图...", "分析", "意图分析器")
        
        # 分析意图
        intent = nlp_tool.analyze_intent(query.text)
        logger_tool.log_workflow(f"用户意图类型: {intent['type']}", "检测", "意图分析器")
        
        # 记录意图工具调用
        logger_tool.log_tool_usage("意图分析", {"query": query.text}, intent, "意图分析器")
        
        # 根据意图类型处理请求
        if intent["type"] == "greeting":
            # 使用CrewAI来处理问候
            try:
                logger_tool.log_workflow("使用CrewAI处理问候...", "INFO")
                
                # 创建一个SmartSupermarketCrew实例处理问候
                smart_crew = SmartSupermarketCrew(model)
                
                # 记录CrewAI使用情况
                logger_tool.log_agent_action("系统", "初始化CrewAI", {"意图": "greeting", "输入": query.text})
                
                # 使用crew处理请求
                crew_result = smart_crew.process_request(query.text)
                
                if crew_result:
                    logger_tool.log_system_response(crew_result, "超市总管理员")
                    response = {
                        "success": True,
                        "message": crew_result,
                        "data": None
                    }
                    # 添加工作流数据
                    workflow = logger_tool.get_workflow()
                    if workflow:
                        response["workflow"] = workflow
                    return response
                
                # 如果crew处理失败，使用默认回复
                response = {
                    "success": True,
                    "message": "您好，这里是智能超市，有什么能帮到您的？\n\n您可以：\n1. 询问商品推荐\n2. 查询商品价格\n3. 购买商品\n4. 查询库存",
                    "data": None
                }
                logger_tool.log_system_response(response["message"], "超市总管理员")
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    response["workflow"] = workflow
                return response
            except Exception as e:
                error_msg = f"处理问候时出错: {str(e)}"
                logger_tool.log_workflow(error_msg, "ERROR")
                response = {
                    "success": False,
                    "message": "抱歉，处理您的问候时出现了错误。",
                    "data": None
                }
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    response["workflow"] = workflow
                return response
        
        elif intent["type"] == "recommendation":
            # 处理商品推荐请求
            try:
                logger_tool.log_workflow("处理商品推荐请求...", "处理", "商品推荐专家")
                
                # 检测场景
                scene = nlp_tool.detect_scene_from_query(query.text)
                if scene:
                    logger_tool.log_workflow(f"检测到场景: {scene}", "检测", "场景检测器")
                
                # 提取参数
                parameters = intent.get("parameters", {})
                
                # 健身场景特殊处理
                if scene == "健身":
                    logger_tool.log_workflow(f"处理健身相关场景: {scene}", "处理", "健身推荐专家")
                    logger_tool.log_agent_action("商品推荐专家", "分析健身需求", {"查询": query.text, "场景": scene})
                    logger_tool.log_tool_usage("健身场景推荐查询", {"scene": scene, "query": query.text}, None, "商品推荐专家")
                    
                    # 调用健身场景推荐
                    fitness_result = product_tool.get_fitness_recommendations(query.text)
                    
                    # 在控制台打印健身推荐的处理过程
                    print("获取健身推荐:", query.text)
                    print("健身子场景:", scene)
                    
                    # 获取场景相关的类别
                    categories = nlp_tool.get_categories_for_scene(scene)
                    print("场景相关类别:", categories)
                    
                    # 获取场景相关的产品
                    # 删除或注释掉不存在的方法调用
                    # scene_products = product_tool.get_products_for_scene(scene)
                    # print("场景相关商品:", scene_products)
                    
                    logger_tool.log_agent_action("商品推荐专家", "提供健身推荐", {"推荐商品数量": 5, "推荐场景": scene})
                    logger_tool.log_agent_action("商品推荐专家", "完成健身推荐", {"状态": "成功", "结果类型": "健身商品推荐"})
                    logger_tool.log_agent_delegation("商品推荐专家", "超市总管理员", "返回健身推荐结果", "推荐流程已完成")
                    
                    logger_tool.log_system_response(fitness_result["message"], "健身推荐专家")
                    
                    # 添加工作流数据
                    workflow = logger_tool.get_workflow()
                    if workflow:
                        fitness_result["workflow"] = workflow
                    return fitness_result
                
                # 如果有场景但没有特殊处理，使用场景推荐
                if scene:
                    logger_tool.log_workflow(f"使用场景推荐: {scene}", "使用", "场景推荐器")
                    logger_tool.log_agent_action("商品推荐专家", "分析场景需求", {"查询": query.text, "场景": scene})
                    logger_tool.log_tool_usage("场景推荐查询", {"scene": scene}, None, "商品推荐专家")
                    
                    # 获取场景相关的类别
                    categories = nlp_tool.get_categories_for_scene(scene)
                    logger_tool.log_workflow(f"场景相关类别: {categories}", "分析", "商品推荐专家")
                    logger_tool.log_agent_action("商品推荐专家", "获取场景类别", {"场景": scene, "类别": categories})
                    
                    # 使用场景推荐功能
                    logger_tool.log_tool_usage("场景推荐商品搜索", {"scene": scene, "limit": 5})
                    scene_result = product_tool.get_scene_recommendations(scene, 5)
                    logger_tool.log_agent_action("商品推荐专家", "完成场景推荐", {"状态": scene_result["success"], "场景": scene})
                    
                    if scene_result["success"]:
                        logger_tool.log_agent_delegation("商品推荐专家", "超市总管理员", "返回场景推荐结果", "推荐流程已完成")
                        logger_tool.log_system_response(scene_result["message"], "商品推荐专家")
                        
                        # 添加工作流数据
                        workflow = logger_tool.get_workflow()
                        if workflow:
                            scene_result["workflow"] = workflow
                        return scene_result
                
                # 根据意图参数进行搜索
                products = []
                
                # 尝试使用不同的参数进行搜索
                if parameters:
                    # 按类别搜索
                    if parameters.get("category"):
                        category = parameters.get("category")
                        
                        logger_tool.log_agent_action("商品推荐专家", "准备按类别搜索", {"类别": category, "查询": query.text})
                        logger_tool.log_tool_usage("类别搜索", {"category": category})
                        
                        category_result = product_tool.get_products_by_category(category, 5)
                        logger_tool.log_agent_action("商品推荐专家", "完成类别搜索", {"状态": category_result["success"]})
                        
                        if category_result["success"]:
                            logger_tool.log_agent_delegation("商品推荐专家", "超市总管理员", "返回类别搜索结果", "搜索流程已完成")
                            logger_tool.log_system_response(category_result["message"], "商品推荐专家")
                            
                            # 添加工作流数据
                            workflow = logger_tool.get_workflow()
                            if workflow:
                                category_result["workflow"] = workflow
                            return category_result
                            
                    elif intent["parameters"].get("product") and len(intent["parameters"]["product"]) > 0:
                        # 按产品名称搜索
                        product_name = intent["parameters"]["product"][0]
                        
                        logger_tool.log_agent_action("商品推荐专家", "准备按产品名称搜索", {"产品名称": product_name, "查询": query.text})
                        logger_tool.log_tool_usage("产品名称搜索", {"product_name": product_name})
                        
                        name_result = product_tool.get_products_by_name(product_name, 5)
                        logger_tool.log_agent_action("商品推荐专家", "完成产品名称搜索", {"状态": name_result["success"]})
                        
                        if name_result["success"]:
                            logger_tool.log_agent_delegation("商品推荐专家", "超市总管理员", "返回产品名称搜索结果", "搜索流程已完成")
                            logger_tool.log_system_response(name_result["message"], "商品推荐专家")
                            
                            # 添加工作流数据
                            workflow = logger_tool.get_workflow()
                            if workflow:
                                name_result["workflow"] = workflow
                            return name_result
                            
                    else:
                        # 使用关键词搜索
                        keywords = query.text
                        
                        logger_tool.log_agent_action("商品推荐专家", "准备按关键词搜索", {"关键词": keywords})
                        logger_tool.log_tool_usage("关键词搜索", {"keywords": keywords})
                        
                        keyword_result = product_tool.search_products_by_keywords(keywords, 5)
                        logger_tool.log_agent_action("商品推荐专家", "完成关键词搜索", {"状态": keyword_result["success"]})
                        
                        if keyword_result["success"]:
                            logger_tool.log_agent_delegation("商品推荐专家", "超市总管理员", "返回关键词搜索结果", "搜索流程已完成")
                            logger_tool.log_system_response(keyword_result["message"], "搜索引擎")
                            
                            # 添加工作流数据
                            workflow = logger_tool.get_workflow()
                            if workflow:
                                keyword_result["workflow"] = workflow
                            return keyword_result
                
                # 如果没有找到商品，使用ProductTool进行更全面的搜索
                if not products:
                    logger_tool.log_tool_usage("全文搜索商品", {"query": query.text})
                    search_result = product_tool.search_products(query.text)
                    if search_result["success"]:
                        logger_tool.log_system_response(search_result["message"], "商品推荐专家")
                        
                        # 添加工作流数据
                        workflow = logger_tool.get_workflow()
                        if workflow:
                            search_result["workflow"] = workflow
                        return search_result
                
                # 如果还是没有找到商品，返回热门商品
                if not products:
                    logger_tool.log_tool_usage("获取热门商品", {"limit": 5})
                    products = db_tool.get_popular_products(5)

                # 生成推荐文案
                logger_tool.log_workflow("生成推荐文案...", "生成", "商品推荐专家")
                recommendation_text = nlp_tool.generate_recommendation_text(products, query.text)
                
                response = {
                    "success": True,
                    "message": recommendation_text,
                    "data": {
                        "products": products[:5],
                        "total_found": len(products)
                    }
                }
                logger_tool.log_system_response(response["message"], "商品推荐专家")
                
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    response["workflow"] = workflow
                return response
            except Exception as e:
                error_msg = f"处理商品推荐时出错: {str(e)}"
                logger_tool.log_workflow(error_msg, "ERROR")
                response = {
                    "success": False,
                    "message": "抱歉，处理商品推荐时出现错误。",
                    "data": None
                }
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    response["workflow"] = workflow
                return response
        
        elif intent["type"] == "purchase":
            # 处理购买请求
            try:
                logger_tool.log_workflow("处理购买请求...", "处理", "库存管理员")
                result = inventory_tool.handle_purchase_intent(intent.get("query", query.text))
                logger_tool.log_system_response(result["message"], "库存管理员")
                
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    result["workflow"] = workflow
                return result
            except Exception as e:
                error_msg = f"处理购买请求时出错: {str(e)}"
                logger_tool.log_workflow(error_msg, "ERROR")
                response = {
                    "success": False,
                    "message": "抱歉，处理购买请求时出现错误。",
                    "data": None
                }
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    response["workflow"] = workflow
                return response
        
        elif intent["type"] == "payment":
            # 处理支付请求
            try:
                logger_tool.log_workflow("处理支付请求...", "处理", "收银员")
                # 获取支付参数
                parameters = intent.get("parameters", {})
                payment_method = parameters.get("payment_method", "现金")
                
                # 调用支付工具
                logger_tool.log_agent_action("收银员", "准备处理支付", {"支付方式": payment_method, "查询": query.text})
                logger_tool.log_tool_usage("支付处理", {"payment_method": payment_method, "query": query.text})
                
                result = payment_tool.process_payment(intent.get("query", query.text), payment_method)
                logger_tool.log_agent_action("收银员", "完成支付处理", {"状态": result["success"], "支付方式": payment_method})
                
                logger_tool.log_system_response(result["message"], "收银员")
                
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    result["workflow"] = workflow
                return result
            except Exception as e:
                error_msg = f"处理支付请求时出错: {str(e)}"
                logger_tool.log_workflow(error_msg, "ERROR")
                response = {
                    "success": False,
                    "message": "抱歉，处理支付请求时出现错误。",
                    "data": None
                }
                # 添加工作流数据
                workflow = logger_tool.get_workflow()
                if workflow:
                    response["workflow"] = workflow
                return response
        
        elif intent["type"] == "inventory":
            # 库存查询
            product_name = intent.get("parameters", {}).get("product", [""])[0]
            logger_tool.log_agent_action("库存管理员", "准备查询库存", {"产品名称": product_name, "查询": query.text})
            
            if not product_name:
                logger_tool.log_agent_action("库存管理员", "库存查询失败", {"原因": "未指定产品名称"})
                response = {
                    "success": False,
                    "message": "请告诉我您想查询哪种商品的库存",
                    "data": None
                }
            else:
                logger_tool.log_workflow(f"查询商品库存: {product_name}", "INFO", "库存管理员")
                logger_tool.log_tool_usage("库存查询", {"product_name": product_name})
                result = inventory_tool.check_inventory(product_name)
                logger_tool.log_agent_action("库存管理员", "完成库存查询", {"状态": result["success"], "产品": product_name})
                
                response = {
                    "success": result["success"],
                    "message": result["message"],
                    "data": result["data"] if result["success"] else None
                }
                logger_tool.log_agent_delegation("库存管理员", "超市总管理员", "返回库存查询结果", "查询流程已完成")
            
            # 添加工作流数据
            workflow = logger_tool.get_workflow()
            if workflow:
                response["workflow"] = workflow
            return response
        
        elif intent["type"] == "general_question":
            response = {
                "success": True,
                "message": intent.get("message", "您可以这样使用我们的服务：\n\n1. 商品推荐：'推荐一些水果'\n2. 购买商品：'用现金购买10斤苹果'\n3. 查询库存：'苹果还有多少库存'\n4. 查询价格：'苹果多少钱一斤'\n\n请问您需要哪方面的帮助？"),
                "data": None
            }
            logger_tool.log_system_response(response["message"])
            
            # 添加工作流数据
            workflow = logger_tool.get_workflow()
            if workflow:
                response["workflow"] = workflow
            return response
        
        elif intent["type"] == "error":
            response = {
                "success": False,
                "message": intent.get("message", "抱歉，系统处理您的请求时出现错误，请重试。"),
                "data": None
            }
            logger_tool.log_system_response(response["message"])
            
            # 添加工作流数据
            workflow = logger_tool.get_workflow()
            if workflow:
                response["workflow"] = workflow
            return response

        # 如果是未知意图，尝试使用ProductTool进行搜索
        logger_tool.log_workflow("未识别的意图，尝试搜索相关商品...", "INFO")
        search_result = product_tool.search_products(query.text)
        if search_result["success"]:
            logger_tool.log_system_response(search_result["message"], "商品推荐专家")
            
            # 添加工作流数据
            workflow = logger_tool.get_workflow()
            if workflow:
                search_result["workflow"] = workflow
            return search_result
        
        # 如果搜索也失败，返回默认回复
        response = {
            "success": False,
            "message": "抱歉，我不太理解您的需求。您可以：\n1. 询问商品推荐\n2. 查询商品价格\n3. 购买商品\n4. 查询库存",
            "data": None
        }
        logger_tool.log_system_response(response["message"], "商品推荐专家")
        
        # 添加工作流数据
        workflow = logger_tool.get_workflow()
        if workflow:
            response["workflow"] = workflow
        return response

    except Exception as e:
        error_msg = f"处理查询时出错: {str(e)}"
        logger_tool.log_workflow(error_msg, "ERROR")
        response = {
            "success": False,
            "message": f"处理请求时出错: {str(e)}",
            "data": None
        }
        # 添加工作流数据
        workflow = logger_tool.get_workflow()
        if workflow:
            response["workflow"] = workflow
        return response

@app.post("/v1/chat/completions")
async def chat_completions(request: ChatCompletionRequest):
    if not model:
        raise HTTPException(status_code=500, detail="服务未初始化")
    
    try:
        query_prompt = request.messages[-1].content
        print(f"用户问题是: {query_prompt}")

        # 处理用户查询
        result = await process_query(Query(text=query_prompt))
        formatted_response = json.dumps(result, ensure_ascii=False)
        print(f"处理结果: {formatted_response}")

        # 处理流式响应
        if request.stream:
            async def generate_stream():
                chunk_id = f"chatcmpl-{uuid.uuid4().hex}"
                lines = formatted_response.split('\n')
                for i, line in enumerate(lines):
                    chunk = {
                        "id": chunk_id,
                        "object": "chat.completion.chunk",
                        "created": int(time.time()),
                        "choices": [
                            {
                                "index": 0,
                                "delta": {"content": line + '\n'},
                                "finish_reason": None
                            }
                        ]
                    }
                    yield f"{json.dumps(chunk)}\n"
                    await asyncio.sleep(0.5)

                final_chunk = {
                    "id": chunk_id,
                    "object": "chat.completion.chunk",
                    "created": int(time.time()),
                    "choices": [
                        {
                            "index": 0,
                            "delta": {},
                            "finish_reason": "stop"
                        }
                    ]
                }
                yield f"{json.dumps(final_chunk)}\n"

            return StreamingResponse(generate_stream(), media_type="text/event-stream")
        else:
            response = ChatCompletionResponse(
                choices=[
                    ChatCompletionResponseChoice(
                        index=0,
                        message=Message(role="assistant", content=formatted_response),
                        finish_reason="stop"
                    )
                ]
            )
            return JSONResponse(content=response.model_dump())

    except Exception as e:
        print(f"处理聊天完成时出错: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

class SmartSupermarket:
    def __init__(self):
        # 初始化模型
        self.llm = ChatOpenAI(
            base_url="http://localhost:3000/v1",
            api_key="sk-M7C40emVuDhbUmwhD560F8A8F4D144Bd974aD5BcE2D24d9d",
            model="ERNIE-Speed-128K",
            temperature=0.7
        )
        
        # 初始化crew
        self.crew = SmartSupermarketCrew(self.llm)

    def process_request(self, user_input: str):
        """处理用户请求"""
        return self.crew.process_request(user_input)

def main():
    supermarket = SmartSupermarket()
    
    print("\n欢迎使用智能超市系统！")
    print("您可以：")
    print("1. 询问商品推荐")
    print("2. 查询商品库存")
    print("3. 购买商品")
    print("4. 或者其他任何问题\n")
    
    while True:
        user_input = input("\n请输入您的需求（输入'退出'结束）: ")
        if user_input.lower() in ['退出', 'exit', 'quit']:
            print("\n感谢使用智能超市系统，再见！")
            break
            
        try:
            result = supermarket.process_request(user_input)
            print("\n系统回复:", result)
        except Exception as e:
            print(f"\n处理请求时出错: {str(e)}")

if __name__ == "__main__":
    print(f"在端口 {PORT} 上启动服务器")
    uvicorn.run(app, host="0.0.0.0", port=PORT)
